package com.cskaoyan.service.wx;
import com.cskaoyan.bean.MarketStorage;
import com.cskaoyan.mapper.MarketStorageMapper;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author : qj
 * @since: 2022/10/15  18:55
 */

@Service
@ConfigurationProperties(prefix = "devconfig")
@Data
public class WxStorageServiceImpl implements WxStorageService{
    @Autowired
    MarketStorageMapper marketStorageMapper;
    String ip ;
    @Override
    public MarketStorage uploadFile(MultipartFile file) {
        //文件类型
        String type = file.getContentType();
        //文件原始名字
        String name = file.getOriginalFilename();
        //文件的大小
        int size = (int) file.getSize();
        //获取uuid
        UUID uuid = UUID.randomUUID();
        int index = type.indexOf("/");
        //将uuid与 ".jpg"拼接起来作为文件的唯一标识
        String key = uuid.toString() + "." + type.substring(index + 1);
        String url = ip + "/wx/storage/fetch/" + key;
        File destPath = new File("d:\\spring/wx/storage/fetch/", key);
        //将文件保存到磁盘中
        try {
            file.transferTo(destPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //new File("");
        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setKey(key);
        marketStorage.setName(name);
        marketStorage.setSize(size);
        marketStorage.setType(type);
        marketStorage.setUrl(url);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String addTime = sdf.format(new Date());
        Date time = null;
        try {
            time = sdf.parse(addTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        marketStorage.setAddTime(time);
        marketStorage.setUpdateTime(time);

        marketStorageMapper.insertSelective(marketStorage);

        return marketStorage;
    }
}
